package com.rt.gptnext.common.utils.json;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONPath;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.TypeReference;
import com.alibaba.fastjson2.filter.Filter;
import com.alibaba.fastjson2.util.TypeUtils;

/**
 * @author gaoyiyang
 **/
public class JsonUtil {

	/**
	 * 返回安全的json字符串
	 *
	 * @param o 待转换对象
	 * @return 安全的json字符串
	 */
	public static String toSafeJsonString(Object o) {
		if (o instanceof String && JSONUtil.isTypeJSON((String) o)) {
			o = JSON.parse((String) o);
		}
		return JSON.toJSONString(o, DatePattern.NORM_DATETIME_PATTERN, new Filter[]{new MultipleValueFilter(FieldLengthSplitFilter.INSTANCE, FieldStarFilter.INSTANCE)},
			JSONWriter.Feature.WriteNullStringAsEmpty,
			JSONWriter.Feature.WriteEnumsUsingName,
			JSONWriter.Feature.WriteMapNullValue,
			JSONWriter.Feature.MapSortField,
			JSONWriter.Feature.WriteBigDecimalAsPlain,
			JSONWriter.Feature.WriteLongAsString
		);
	}

	/**
	 * 返回格式化的json字符串
	 *
	 * @param o 待转换对象
	 * @return 格式化的json字符串
	 */
	public static String toPrettyJsonString(Object o) {
		return JSON.toJSONString(o, DatePattern.NORM_DATETIME_PATTERN,
			JSONWriter.Feature.WriteNullStringAsEmpty,
			JSONWriter.Feature.WriteMapNullValue,
			JSONWriter.Feature.WriteEnumsUsingName,
			JSONWriter.Feature.WriteBigDecimalAsPlain,
			JSONWriter.Feature.MapSortField,
			JSONWriter.Feature.WriteLongAsString,
			JSONWriter.Feature.PrettyFormat
		);
	}

	/**
	 * 返回json字符串
	 *
	 * @param o 待转换对象
	 * @return 格式化的json字符串
	 */
	public static String toJsonString(Object o) {
		return JSON.toJSONString(o, DatePattern.NORM_DATETIME_PATTERN,
			JSONWriter.Feature.WriteNullStringAsEmpty,
			JSONWriter.Feature.WriteMapNullValue,
			JSONWriter.Feature.WriteEnumsUsingName,
			JSONWriter.Feature.WriteBigDecimalAsPlain,
			JSONWriter.Feature.MapSortField,
			JSONWriter.Feature.WriteLongAsString
		);
	}

	/**
	 * 通过jsonpath获取值
	 *
	 * @param o           原始json对象
	 * @param jsonPath    jsonpath
	 * @param targetClass 目标类型
	 * @return 结果值
	 */
	public static <T> T getByJsonPath(Object o, String jsonPath, Class<T> targetClass) {
		return getByJsonPath(o, jsonPath, (TypeReference<T>) TypeReference.get(targetClass));
	}

	/**
	 * 通过jsonpath获取值
	 *
	 * @param o             原始json对象
	 * @param jsonPath      jsonpath
	 * @param typeReference 目标类型
	 * @return 结果值
	 */
	public static <T> T getByJsonPath(Object o, String jsonPath, TypeReference<T> typeReference) {
		JSONPath jp = JSONPath.of(jsonPath);
		Object result = null;
		if (o instanceof byte[]) {
			result = jp.extract((byte[]) o);
		} else if (o instanceof String) {
			result = jp.extract((String) o);
		} else {
			result = jp.eval(o);
		}
		return TypeUtils.cast(result, typeReference.getType());
	}

}
